//
//  NewRankVC.m
//  WanCaiC8
//
//  Created by tangang on 2018/3/5.
//  Copyright © 2018年 tangang. All rights reserved.
//

#import "MasterRankVC.h"
#import "LabCell.h"
#import "PlanTypeView.h"
#import "LotteryTypeView.h"
#import "MasterCell.h"
#import "HomePageVM.h"
#import "MJRefresh.h"
#import "RankBottomView.h"
#import "RankTopView.h"
#import "OtherInfoVC.h"
#import "PlanPeopleTotalVC.h"
@interface MasterRankVC () <UITableViewDataSource,UITableViewDelegate,UICollectionViewDelegate,UICollectionViewDataSource>
@property (nonatomic ,strong) UICollectionView *collectionView;
@property (nonatomic ,strong) UITableView *tableView;
@property (nonatomic ,strong) NSMutableArray *dataArr;
@property (nonatomic ,strong) NSMutableArray *typeArr;
@property (nonatomic ,strong) NSMutableArray *lotteryArr;
@property (nonatomic ,strong) PlanTypeView  *typeView;
@property (nonatomic ,strong) LotteryTypeView  *lotteryTypeView;
@property (nonatomic ,strong) RankBottomView   *bottomView;
@end

@implementation MasterRankVC{
    NSInteger   selectType;
    BOOL        isAll;
    NSInteger   selectBType;
    NSInteger   selectSType;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    selectType=3;
    isAll=YES;
    [self.tableView.header beginRefreshing];
}

- (void)getData{
    if (self.type==RankTypeFans) {
        self.title=@"粉丝榜";
        [self getFansData];
    }else if (self.type==RankTypeMaster){
        self.title=@"彩票高手榜";
        [self getTotal];
    }else if (self.type==RankTypeIntegral){
        self.title=@"积分榜";
        [self getIntegralData];
    }else if (self.type==RankTypeProfit){
        self.title=@"盈利榜";
        [self getTotal];
    }else if (self.type==RankTypeExceptional){
        self.title=@"打赏榜";
        [self getTotal];
    }
}

#pragma mark -- 获取盈利打赏榜数据
- (void)getProfitRewardList{
    WS(weakSelf);
    LotteryTypeModel *model=self.lotteryArr[selectSType];
    [[HomePageVM manage] getProfitRewardListWithId:[model.lType integerValue] andQueryType:selectType andRType:self.type Success:^(id returnValue) {
        [weakSelf.tableView.footer noticeNoMoreData];
        NSArray *arr=returnValue;
        BOOL isHave=NO;
        for (RankingUserModel *model in arr) {
            if ([model.UserId isEqualToString:[UserModel userModel].UserId]) {
                isHave=YES;
                weakSelf.bottomView.rankingUserModel=model;
                break;
            }
        }
        
        if (!isHave) {
            [weakSelf getMyProfitRewardBang:[model.lType integerValue]];
        }
        
        [weakSelf.dataArr addObjectsFromArray:returnValue];
        [weakSelf.tableView.header endRefreshing];
        if (isAll) {
            weakSelf.tableView.tableHeaderView=[self tabHeadView];
        }else{
            weakSelf.tableView.tableHeaderView=nil;
        }
        [weakSelf.tableView reloadData];
    } andFail:^(NSString *errorMessage, NSError *error) {
        [weakSelf.tableView.header endRefreshing];
        [weakSelf.tableView.footer endRefreshing];
    }];
    
    
}

- (void)getMyProfitRewardBang:(NSInteger)lType{
    WS(weakSelf);
    [[HomePageVM manage] getMyProfitRewardBangWithId:lType andQueryType:selectType andRType:self.type Success:^(id returnValue) {
        weakSelf.bottomView.rankingUserModel=returnValue;
    } andFail:^(NSString *errorMessage, NSError *error) {
        
    }];
}

#pragma mark -- 获取积分榜数据
- (void)getIntegralData{
    WS(weakSelf);
    [[HomePageVM manage] getIntegralListWithQueryType:selectType Success:^(id returnValue) {
        NSArray *arr=returnValue;
        [weakSelf.tableView.footer noticeNoMoreData];
        BOOL isHave=NO;
        for (RankingUserModel *model in arr) {
            if ([model.UserId isEqualToString:[UserModel userModel].UserId]) {
                isHave=YES;
                weakSelf.bottomView.rankingUserModel=model;
                break;
            }
        }
        
        if (!isHave) {
            [weakSelf getMyBangRank];
        }
        
        [weakSelf.dataArr addObjectsFromArray:returnValue];
        [weakSelf.tableView.header endRefreshing];
        if (isAll) {
            weakSelf.tableView.tableHeaderView=[self tabHeadView];
        }else{
            weakSelf.tableView.tableHeaderView=nil;
        }
        [weakSelf.tableView reloadData];
    } andFail:^(NSString *errorMessage, NSError *error) {
        [weakSelf.tableView.header endRefreshing];
        [weakSelf.tableView.footer endRefreshing];
    }];
    
    
}



#pragma mark -- 获取粉丝榜数据
- (void)getFansData{
    NSString *type=@"day";
    if (selectType==1) {
        type=@"week";
    }else if (selectType==2){
        type=@"month";
    }else if (selectType==3){
        type=@"all";
    }
    WS(weakSelf);
    [[HomePageVM manage] getFansBangList:type andPageIndex:1 andSuccess:^(id returnValue) {
        NSArray *arr=returnValue;
        if (arr.count<[defaultPageSize integerValue]) {
            [weakSelf.tableView.footer noticeNoMoreData];
        }else{
            [weakSelf.tableView.footer endRefreshing];
        }
        [weakSelf.dataArr addObjectsFromArray:returnValue];
        [weakSelf.tableView.header endRefreshing];
        if (isAll) {
            weakSelf.tableView.tableHeaderView=[self tabHeadView];
        }else{
            weakSelf.tableView.tableHeaderView=nil;
        }
        [weakSelf.tableView reloadData];
        BOOL isHave=NO;
        for (RankingUserModel *model in arr) {
            if ([model.UserId isEqualToString:[UserModel userModel].UserId]) {
                isHave=YES;
                weakSelf.bottomView.rankingUserModel=model;
                break;
            }
        }
        if (!isHave) {
            [weakSelf getMyBangRank];
        }
    } andFail:^(NSString *errorMessage, NSError *error) {
        [weakSelf.tableView.header endRefreshing];
        [weakSelf.tableView.footer endRefreshing];
    }];
    
    
}

#pragma mark -- 获取所有彩种
- (void)getTotal{
    WS(weakSelf);

    [[HomePageVM manage] getLotteryTypeListWithParentId:@"" Success:^(id returnValue) {
        [weakSelf createData];
    } Fail:^(NSString *errorMessage, NSError *error) {
        
    }];
}

- (void)createData{
    [self.lotteryArr removeAllObjects];
    LotteryTypeModel *lModel=[BaseVM manage].lotteryArr[selectBType];
    for (LotteryTypeModel *model in [HomePageVM manage].total) {
        if ([model.PId isEqualToString:lModel.Id]) {
            [self.lotteryArr addObject:model];
        }
    }
    self.typeView.arrData=self.lotteryArr;
    if (self.type==RankTypeMaster) {
        [self getMasterData];
    }else if (self.type==RankTypeExceptional||self.type==RankTypeProfit){
        [self getProfitRewardList];
    }
    
}

#pragma mark -- 获取高手榜数据
- (void)getMasterData{
    WS(weakSelf);
    LotteryTypeModel *model=self.lotteryArr[selectSType];
    [[HomePageVM manage] getHighMasterListWithId:[model.lType integerValue] andQueryType:selectType Success:^(id returnValue) {
        NSArray *arr=returnValue;
        if (arr.count<[defaultPageSize integerValue]) {
            [weakSelf.tableView.footer noticeNoMoreData];
        }else{
            [weakSelf.tableView.footer endRefreshing];
        }
        [weakSelf.dataArr addObjectsFromArray:returnValue];
        [weakSelf.tableView.header endRefreshing];
        if (isAll) {
            weakSelf.tableView.tableHeaderView=[self tabHeadView];
        }else{
            weakSelf.tableView.tableHeaderView=nil;
        }
        BOOL isHave=NO;
        for (RankingUserModel *model in arr) {
            if ([model.UserId isEqualToString:[UserModel userModel].UserId]) {
                isHave=YES;
                weakSelf.bottomView.rankingUserModel=model;
                break;
            }
        }
        if (!isHave) {
            [weakSelf getMyBangRank];
        }
        [weakSelf.tableView reloadData];
    } andFail:^(NSString *errorMessage, NSError *error) {
        [weakSelf.tableView.header endRefreshing];
        [weakSelf.tableView.footer endRefreshing];
    }];
    
    
}

///获取我的排行
- (void)getMyBangRank{
    WS(weakSelf);
    if (self.type==RankTypeFans) {
        WS(weakSelf);
        NSString *type=@"day";
        if (selectType==1) {
            type=@"week";
        }else if (selectType==2){
            type=@"month";
        }else if (selectType==3){
            type=@"all";
        }
        [[HomePageVM manage] getMyFansBangRanking:type andSuccess:^(id returnValue) {
            weakSelf.bottomView.rankingUserModel=returnValue;
        } andFail:^(NSString *errorMessage, NSError *error) {
            
        }];
    }else if (self.type==RankTypeMaster){
        LotteryTypeModel *model=self.lotteryArr[selectSType];
        [[HomePageVM manage] getMyMasterBangRanking:selectType andLType:[model.lType integerValue] andSuccess:^(id returnValue) {
            weakSelf.bottomView.rankingUserModel=returnValue;
        } andFail:^(NSString *errorMessage, NSError *error) {
            
        }];
    }else if (self.type==RankTypeIntegral){
        WS(weakSelf);
        [[HomePageVM manage] getIntegralBangWithQueryType:selectType Success:^(id returnValue) {
            weakSelf.bottomView.rankingUserModel=returnValue;
        } andFail:^(NSString *errorMessage, NSError *error) {
            
        }];
    }else if (self.type==RankTypeProfit){
        self.title=@"盈利榜";
        [self getTotal];
    }else if (self.type==RankTypeExceptional){
        self.title=@"打赏榜";
        [self getTotal];
    }
    
}



#pragma mark -- UITableViewDelegate ,UITableViewDataSource
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (isAll) {
        return self.dataArr.count<3?0:self.dataArr.count-3;
    }else{
        return self.dataArr.count;
    }
    
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MasterCell *cell=[tableView dequeueReusableCellWithIdentifier:@"MasterCell" forIndexPath:indexPath];
    if (isAll) {
        cell.model=self.dataArr[indexPath.row+3];
    }else{
        cell.model=self.dataArr[indexPath.row];
    }
    cell.type=self.type;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (self.type==RankTypeMaster) {
        PlanPeopleTotalVC *vc=[[PlanPeopleTotalVC alloc]init];
        RankingUserModel *userModel;
        if (isAll) {
            userModel=self.dataArr[indexPath.row+3];
        }else{
            userModel=self.dataArr[indexPath.row];
        }
        ExpertsModel *model =[[ExpertsModel alloc]init];
        model.UserId=userModel.UserId;
        vc.model=model;
        LotteryTypeModel *lotteryModel=self.lotteryArr[selectSType];;
        vc.lotteryModel=lotteryModel;
        vc.title=[NSString stringWithFormat:@"%@近期竞猜",lotteryModel.Name];
        
        [self.navigationController pushViewController:vc animated:YES];
    }else{
//        OtherInfoVC *vc=[[OtherInfoVC alloc]init];
//        RankingUserModel *model;
//        if (isAll) {
//            model=self.dataArr[indexPath.row+3];
//        }else{
//            model=self.dataArr[indexPath.row];
//        }
//        vc.userId=model.FollowedUserId;
//        [self.navigationController pushViewController:vc animated:YES];
    }
}

#pragma mark - collectionView代理函数
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.typeArr.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    LabCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"LabCell" forIndexPath:indexPath];
    [cell setBottomLineTitle:self.typeArr[indexPath.row] andIsSelect:indexPath.row==selectType];
    return cell;
}

-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(0, 0, 0, 0);
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row!=selectType) {
        selectType=indexPath.row;
        [collectionView reloadData];
        isAll=(indexPath.row==3);
        [self.tableView.header beginRefreshing];
    }
    
}

#pragma mark -- 懒加载
- (UITableView *)tableView{
    if (!_tableView) {
        WS(weakSelf);
        _tableView=[[UITableView alloc]init];
        _tableView.dataSource=self;
        _tableView.delegate=self;
        _tableView.rowHeight=UITableViewAutomaticDimension;
        _tableView.estimatedRowHeight=60;
        [_tableView registerClass:[MasterCell class] forCellReuseIdentifier:@"MasterCell"];
        _tableView.backgroundColor=DEFAULTBGCOLOR;
        _tableView.header=[MJRefreshNormalHeader headerWithRefreshingBlock:^{
            [weakSelf.dataArr removeAllObjects];
            [weakSelf.tableView reloadData];
            [weakSelf getData];
        }];
        _tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
        [self.view addSubview:_tableView];
        [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(self.view);
            make.bottom.equalTo(self.bottomView.mas_top);
            make.top.equalTo(self.collectionView.mas_bottom)
            .with.offset(5);
        }];
    }
    return _tableView;
}

- (RankBottomView *)bottomView{
    if (!_bottomView) {
        _bottomView=[[RankBottomView alloc]init];
        [self.view addSubview:_bottomView];
        [_bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.equalTo(self.view);
            make.height.mas_equalTo(@75);
        }];
    }
    return _bottomView;
}

- (UICollectionView *)collectionView{
    if (!_collectionView) {
        WS(weakSelf);
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        [layout setItemSize:CGSizeMake(SCREEN_WIDTH/4.0, 39)];
        [layout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
        layout.minimumInteritemSpacing = 0.0;
        layout.minimumLineSpacing = 0.0;
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        _collectionView.backgroundColor = [UIColor whiteColor];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.showsHorizontalScrollIndicator=NO;
        [_collectionView registerClass:[LabCell class] forCellWithReuseIdentifier:@"LabCell"];
        [self.view addSubview:_collectionView];
        if (self.type==RankTypeIntegral||self.type==RankTypeFans||self.type==RankTypeAnswer) {
            [_collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.top.right.equalTo(weakSelf.view);
                make.height.mas_equalTo(@(real_size(39)));
            }];
        }else{
            [_collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.right.equalTo(weakSelf.view);
                make.top.equalTo(self.typeView.mas_bottom);
                make.height.mas_equalTo(@(real_size(39)));
            }];
        }
    }
    return _collectionView;
}

- (NSMutableArray *)dataArr{
    if (!_dataArr) {
        _dataArr=[[NSMutableArray alloc]init];
    }
    return _dataArr;
}

- (NSMutableArray *)lotteryArr{
    if (!_lotteryArr) {
        _lotteryArr=[[NSMutableArray alloc]init];
    }
    return _lotteryArr;
}

- (NSMutableArray *)typeArr{
    if (!_typeArr) {
        _typeArr=[[NSMutableArray alloc]initWithObjects:@"日榜",@"周榜",@"月榜",@"总榜", nil];
    }
    return _typeArr;
}

- (PlanTypeView *)typeView{
    if (!_typeView) {
        WS(weakSelf);
        _typeView=[[PlanTypeView alloc]init];
        _typeView.backgroundColor=[UIColor whiteColor];
        _typeView.changeOpen = ^(BOOL isOpen ,NSArray *dataArr) {
            if (isOpen) {
                [weakSelf.typeView mas_updateConstraints:^(MASConstraintMaker *make) {
                    make.height.mas_equalTo(@(ceilf(dataArr.count/4.0)*40+20));
                }];
            }else{
                [weakSelf.typeView mas_updateConstraints:^(MASConstraintMaker *make) {
                    make.height.mas_equalTo(@60);
                }];
            }
            
        };
        _typeView.changeValue = ^(NSInteger index) {
            selectSType=index;
            [weakSelf.tableView.header beginRefreshing];
        };
        [self.view addSubview:_typeView];
        [_typeView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(weakSelf.view);
            make.top.equalTo(weakSelf.lotteryTypeView.mas_bottom).with.offset(1);
            make.height.mas_equalTo(@60);
        }];
    }
    return _typeView;
}

- (UIView *)tabHeadView{
    
    if (self.dataArr.count==0) {
        return nil;
    }
    
    WS(weakSelf);
    RankTopView *view=[[RankTopView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 131)];
    view.type=self.type;
    view.dataArr=self.dataArr;
    view.backgroundColor=[UIColor whiteColor];
    view.selectBlock = ^(NSInteger index) {
        if (self.type==RankTypeMaster) {
            PlanPeopleTotalVC *vc=[[PlanPeopleTotalVC alloc]init];
            RankingUserModel *userModel=weakSelf.dataArr[index];
            ExpertsModel *model =[[ExpertsModel alloc]init];
            model.UserId=userModel.UserId;
            vc.model=model;
            LotteryTypeModel *lotteryModel=weakSelf.lotteryArr[selectSType];;
            vc.lotteryModel=lotteryModel;
            vc.title=[NSString stringWithFormat:@"%@近期竞猜",lotteryModel.Name];
            [weakSelf.navigationController pushViewController:vc animated:YES];
        }else{
//            OtherInfoVC *vc=[[OtherInfoVC alloc]init];
//            RankingUserModel *model=weakSelf.dataArr[index];
//            vc.userId=model.FollowedUserId;
//            [weakSelf.navigationController pushViewController:vc animated:YES];
        }
        
    };
    return view;
}

- (LotteryTypeView *)lotteryTypeView{
    if (!_lotteryTypeView) {
        WS(weakSelf);
        _lotteryTypeView=[[LotteryTypeView alloc]init];
        _lotteryTypeView.chaneBlock = ^(NSInteger row) {
            selectBType=row;
            [weakSelf.tableView.header beginRefreshing];
        };
        [self.view addSubview:_lotteryTypeView];
        [_lotteryTypeView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.top.right.equalTo(weakSelf.view);
            make.height.mas_equalTo(@40);
        }];
    }
    return _lotteryTypeView;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
